import Vapor

struct ProjectController: RouteCollection {

  func boot(routes: RoutesBuilder) throws {
    let projectRoute = routes.grouped("api", "project")
    projectRoute.post(use: createHandler)
    projectRoute.put(use: updateHandler)

    projectRoute.get(use: getAllHandler)
    projectRoute.get(":projectID", use: getHandler)
    projectRoute.get(":projectID", "simplebuildings", use: getSimpleBuildingsHandler)

  }

  func createHandler(_ req: Request) throws -> EventLoopFuture<Project> {
    let project = try req.content.decode(Project.self)
    return project.save(on: req.db).map { project }
  }
    
func updateHandler(_ req: Request) throws -> EventLoopFuture<Project> {
    let data = try req.content.decode(Project.self)
    return Project.find(data.id, on: req.db).unwrap(or: Abort(.notFound)).flatMap { project in
        project.name = data.name
        project.customLogoID = data.customLogoID
        project.demo = data.demo
        project.ownersEMailAddress = data.ownersEMailAddress
        project.tag = data.tag

        return project.save(on: req.db).map { return project }

    }
}
  
  func getAllHandler(_ req: Request) throws -> EventLoopFuture<[Project]> {
    Project.query(on: req.db).all()
  }

  func getHandler(_ req: Request) throws -> EventLoopFuture<Project> {
    Project.find(req.parameters.get("projectID"), on: req.db).unwrap(or: Abort(.notFound))
  }
  
  func getSimpleBuildingsHandler(_ req: Request) throws -> EventLoopFuture<[SimpleBuilding]> {
    Project.find(req.parameters.get("projectID"), on: req.db).unwrap(or: Abort(.notFound)).flatMap { project in
        project.$simpleBuildings.get(on: req.db)
    }
  }
}
